#include <54func.h>
int main(int argc, char *argv[])
{
    // ./0_server_udp 192.168.72.128 1234 
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = bind(sockfd,(struct sockaddr* )&serverAddr,sizeof(serverAddr));
    // 第一次必须是客户端向服务端发消息
    struct sockaddr_in clientAddr;
    socklen_t socklen = sizeof(clientAddr);
    char buf[4096] = {0};
    recvfrom(sockfd,buf,4096,0,
             (struct sockaddr *)&clientAddr,&socklen); // socklen的设置和accept一样
    printf("buf = %s, ip = %s, port = %d\n", 
           buf, inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
    fd_set rdset;
    while(1){
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(sockfd,&rdset);
        select(sockfd+1,&rdset,NULL,NULL,NULL);
        if(FD_ISSET(sockfd,&rdset)){
            bzero(buf,4096);
            ssize_t sret = recvfrom(sockfd,buf,4096,0,NULL,NULL);
            if(sret == 0){
                break;
            }
            printf("sret = %ld, buf = %s\n", sret, buf);
        }
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            bzero(buf,4096);
            ssize_t sret = read(STDIN_FILENO,buf,4096);
            if(sret == 0){
                // 按下了EOF 发送一个0长度包给对面
                sendto(sockfd,buf,0,0,
                    (struct sockaddr *)&clientAddr,sizeof(clientAddr));
                break;

            }
            sendto(sockfd,buf,strlen(buf),0,
                   (struct sockaddr *)&clientAddr,sizeof(clientAddr));
        }
    }

    return 0;
}

